package com.yonyou.cyxdms.sysAuth.service.service.cms;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.basedata.client.domains.vo.CodeVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonCodeService;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.framework.service.cache.DictCacheServiceImpl;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.StringUtil;
import com.yonyou.cyxdms.sysAuth.service.dto.CodeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.CommonTreeStateDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.role.RolePDto;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.entity.cms.*;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.feign.BaseDataService;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.mapper.cms.CMSEmployeeMapper;
import com.yonyou.cyxdms.sysAuth.service.service.manage.employee.EmployeeService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleService;
import com.yonyou.cyxdms.sysAuth.service.vo.role.PermissionMenuRangeVO;
import com.yonyou.cyxdms.sysAuth.service.vo.role.PermissionMenuVO;
import com.yonyou.cyxdms.sysAuth.service.vo.role.RolePageVO;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.UserRoleDTO;
import com.yonyou.cyxdms.sysmanage.client.vo.role.UserbyRoleVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;


/**
 * 角色信息实现类
 *
 * @author yll
 * @date 2017年5月27日
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class CMSRoleServiceImpl implements CMSRoleService {


    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(com.yonyou.cyxdms.sysAuth.service.service.role.RoleServiceImpl.class);

    @Autowired
    RoleMapper roleMapper;
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    PermissionMenuMapper permissionMenuMapper;
    @Autowired
    CodeMapper codeMapper;
    @Autowired
    PermissionCtrlMapper permissionCtrlMapper;
    @Autowired
    MenuActionMapper menuActionMapper;
    @Autowired
    PermissionMenuActionMapper permissionMenuActionMapper;
    @Autowired
    MenuRangeMapper menuRangeMapper;
    @Autowired
    PermissionMenuRangeMapper permissionMenuRangeMapper;
    @Autowired
    OrgPositionRoleMapper orgPositionRoleMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    DictCacheServiceImpl dictCacheService;

    @Autowired
    private CMSEmployeeMapper employeeMapper;

    @Autowired
    private BaseCommonCodeService baseCommonCodeService;

    @Autowired
    private BaseDataService baseDataService;


    @Override
    public UserInfoInterFaceVO getUserInfo(UserInfoInterFaceDTO userInfoInterFaceDTO) {
        //获取岗位码表
        //List<CodeVO> codeList = baseCommonCodeService.getCodeListByType("2588");
        Map<String, Object> queryParam = new HashMap<String, Object>();
        queryParam.put("type" , 2588);
        RestResultResponse<List<CodeDTO>> res =  baseDataService.queryTcCodeByType(queryParam);
        List<CodeDTO> codeList = res.getData();

        LocalDateTime updateTime = null;
        if (null != userInfoInterFaceDTO.getRecordTime()) {
            Instant instant = Instant.ofEpochMilli(Long.parseLong(userInfoInterFaceDTO.getRecordTime()));
            updateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        }
        List<UserInfoInterFaceMapCp> employeeList = employeeMapper.getUserInfoByUpdateTime(updateTime);
        //RestResultResponse<UserInfoInterFaceVO> res = new RestResultResponse<UserInfoInterFaceVO>();
        UserInfoInterFaceVO data = new UserInfoInterFaceVO();
        //获取最新更新时间作为下次请求时间戳
        employeeList.sort(new Comparator<UserInfoInterFaceMapCp>() {
            @Override
            public int compare(UserInfoInterFaceMapCp o1, UserInfoInterFaceMapCp o2) {
                return (int) (o2.getUpdatedAt() - o1.getUpdatedAt());
            }
        });
        //翻译岗位
        for (UserInfoInterFaceMapCp map : employeeList) {

            //翻译学历
            Map<String , Integer> educationMap = new HashMap();
            educationMap.put("40491001",10351001);
            educationMap.put("40491002",10351002);
            educationMap.put("40491003",10351003);
            educationMap.put("40491004",10351004);
            educationMap.put("40491005",10351005);
            educationMap.put("40491006",10351006);
            Integer education = map.getEducation();
            if(null != education){
                map.setEducation(educationMap.get(education.toString()));
            }
            //翻译第一岗位
            if (!StringUtils.isNullOrEmpty(map.getFirstPose())) {
                for (CodeDTO codeVO : codeList) {
                    if (codeVO.getCodeId() == Integer.parseInt(map.getFirstPose())) {
                        map.setFirstPose(codeVO.getCodeCnDesc());
                        break;
                    }
                }
            }
            //翻译第二岗位
            if (!StringUtils.isNullOrEmpty(map.getSecondPose())) {
                for (CodeDTO codeVO : codeList) {
                    if (codeVO.getCodeId() == Integer.parseInt(map.getSecondPose())) {
                        map.setSecondPose(codeVO.getCodeCnDesc());
                        break;
                    }
                }
            }
            //翻译第三岗位
            if (!StringUtils.isNullOrEmpty(map.getThirdPose())) {
                for (CodeDTO codeVO : codeList) {
                    if (codeVO.getCodeId() == Integer.parseInt(map.getThirdPose())) {
                        map.setThirdPose(codeVO.getCodeCnDesc());
                        break;
                    }
                }
            }

        }

        data.setRecordTime(null == employeeList || employeeList.size() == 0 ? null :
                employeeList.get(0).getUpdatedAt());
        data.setRequestid(userInfoInterFaceDTO.getRequestid());
        data.setList(employeeList);
       /* res.setData(data);
        res.setSuccess(true);
        res.setResultCode(200);
        res.setErrMsg("成功");*/
        return data;
    }


    @Override
    public UserInfoInterZhiHuiVO getUserInfoAll(UserInfoInterFaceDTO userInfoInterFaceDTO) {

        String appId = userInfoInterFaceDTO.getAppId();
        if(StringUtils.isNullOrEmpty(appId)){
            appId = "beijing";
        }
        LocalDateTime updateTime = null;
        if (null != userInfoInterFaceDTO.getRecordTime()) {
            Instant instant = Instant.ofEpochMilli(Long.parseLong(userInfoInterFaceDTO.getRecordTime()));
            updateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        }
        List<UserInfoInterZhiHuiMapCp> employeeList = employeeMapper.getUserInfoAllByUpdateTime(updateTime,userInfoInterFaceDTO.getAppId());
        //RestResultResponse<UserInfoInterFaceVO> res = new RestResultResponse<UserInfoInterFaceVO>();
        UserInfoInterZhiHuiVO data = new UserInfoInterZhiHuiVO();



        //获取最新更新时间作为下次请求时间戳
        employeeList.sort(new Comparator<UserInfoInterZhiHuiMapCp>() {
            @Override
            public int compare(UserInfoInterZhiHuiMapCp o1, UserInfoInterZhiHuiMapCp o2) {
                return (int) (o2.getUpdatedAt() - o1.getUpdatedAt());
            }
        });
        List<CodeVO> listcode = baseCommonCodeService.getCodeListByType(String.valueOf(ManageDictCodeConstants.CHECKEDLIST1));

        if(!employeeList.isEmpty()){
            List<UserInfoInterZhiHuiRoleMapCp> roleList = employeeMapper.getUserInfoRoleAll(appId);
            for (UserInfoInterZhiHuiMapCp user: employeeList){
                List<Map<String,String>> addList = new ArrayList<>();
                Map<String,String> map = new HashMap();
                for (UserInfoInterZhiHuiRoleMapCp role :roleList){
                        if(role.getUserId().equals(user.getUserId())){//用户对应的角色
                            String roleName = role.getRoleName();
                            boolean isRole = false;
                            for (CodeVO vo : listcode) {
                                if(StringUtils.isNullOrEmpty(role.getOrgRoleId())){
                                    isRole = false;
                                    break;
                                }else if (role.getOrgRoleId().equals(vo.getCodeId().toString())) {
                                    roleName = vo.getCodeCnDesc();
                                    isRole = true;
                                    break;
                                }
                            }
                            if(isRole){
                                map.put(role.getOrgRoleId(),roleName);
                            }else{
                                map.put(role.getRoleCode(),roleName);
                            }

                        }
                    }
                addList.add(map);
                user.setRoleCode(addList);
            }
        }

        data.setRecordTime(null == employeeList || employeeList.size() == 0 ? null :
                employeeList.get(0).getUpdatedAt());
        data.setRequestid(userInfoInterFaceDTO.getRequestid());
        data.setList(employeeList);
       /* res.setData(data);
        res.setSuccess(true);
        res.setResultCode(200);
        res.setErrMsg("成功");*/
        return data;
    }


    @Override
    public void updateAutoTime() {
        employeeMapper.updateAutoTime();
    }


}
